<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Classes\UploadImg;
use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\Shop\Goods;
use App\Models\Shop\GoodsClassify;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;

class GoodsController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'classifyID'    =>  'required',
        'title'         =>  'required|max:255',
        'thumb'         =>  'required',
        'price'         =>  'required|numeric',
        'content'       =>  'required'
    ];

    /**
     * 商品管理
     * @return $this
     */
    public function getIndex(Request $request)
    {
        $goods = new Goods();
        if($request->has('goodsClassify'))
        {
            $goods = $goods->where('classifyID', $request->input('goodsClassify'));
        }
        $goods = $goods->orderBy('id', 'desc')->paginate(20);
        //获取商品分类
        $goodsClassify = GoodsClassify::all()->keyBy('id');
        return view('admin.shop.goods')->with(['goods' => $goods, 'goodsClassify' => $goodsClassify]);
    }

    /**
     * 添加商品
     * @return $this
     */
    public function getAdd()
    {
        //获取商品分类
        $goodsClassify = GoodsClassify::orderBy('id', 'desc')->get();
        return view('admin.shop.goods-add')->with(['goodsClassify' => $goodsClassify]);
    }
    public function postAdd(Request $request)
    {
        //验证
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\GoodsController@getAdd')->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $data = [
            'classifyID'    =>  $request->input('classifyID'),
            'title'         =>  $request->input('title'),
            'price'         =>  $request->input('price'),
            'thumb'         =>  $request->input('thumb'),
            'tags'          =>  $request->input('tags'),
            'abstract'      =>  $request->input('abstract'),
            'content'       =>  $request->input('content')
        ];
        //Create
        if (Goods::create($data))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($data));
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\Shop\GoodsController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\Shop\GoodsController@getIndex'), 1);
    }

    /**
     * 修改商品
     * @param $id
     */
    public function getEdit($id)
    {
        //获取商品分类
        $goodsClassify = GoodsClassify::orderBy('id', 'desc')->get();
        //获取商品
        $goods = Goods::find($id);
        return view('admin.shop.goods-edit')->with(['goods' => $goods, 'goodsClassify' => $goodsClassify]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\GoodsController@getEdit', ['id' => $id])->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $data = [
            'classifyID'    =>  $request->input('classifyID'),
            'title'         =>  $request->input('title'),
            'price'         =>  $request->input('price'),
            'thumb'         =>  $request->input('thumb'),
            'tags'          =>  $request->input('tags'),
            'abstract'      =>  $request->input('abstract'),
            'content'       =>  $request->input('content')
        ];
        //修改前的值
        $origin = Goods::find($id)->toArray();
        //Update
        if (Goods::where('id', $id)->update($data))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($data));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\Shop\GoodsController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\Shop\GoodsController@getEdit', ['id' => $id]), 1);
    }

    /**
     * 删除
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        //获取店铺
        $goods = Goods::find($id);
        $origin = $goods->toArray();
        if (!empty($goods))
        {
            if ($goods->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * 上传缩略图
     * @param UploadImg $uploadImg
     * @param Request $request
     */
    public function postUpload(UploadImg $uploadImg, Request $request)
    {
        if ($request->hasFile('avatar_file'))
        {
            if ($request->file('avatar_file')->isValid())
            {
                $avatar_file = $request->file('avatar_file');
                $avatar_data = $request->input('avatar_data');
                $avatar_data_obj = json_decode(stripslashes($avatar_data));
                $date = date('Y-m-d', time());
                $uploadImg->savePath = config('imgUpdate.updatePath').$date.'/';
                //横纵比例
                $prefix = md5(time());
                $aspectRatio = [
                    [
                        'width'     =>  300,
                        'height'    =>  300,
                        'path'      =>  $prefix.'.png'
                    ]
                ];
                $backData = $uploadImg->upThumb($avatar_file, $avatar_data, $aspectRatio);
                if(count($backData) > 0)
                {
                    //返回数据
                    $backData['thumb'] = $date.'.'.$backData['thumb'];
                    $backData['msg'] = '上传成功！';
                    echo json_encode($backData);
                }
            }
        }
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'shop_goods.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'shop_goods.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'shop_goods.delete',
                    'type'  =>  'Delete'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
